package com.pay.download.processor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pay.entity.ZfbInLog;
import com.pay.entity.ZfbMember;
import com.pay.utils.FunctionUtils;

import cn.hutool.core.util.StrUtil;

public class FundAccountDetailProcessor {

	/**
	 * 处理器
	 * @return
	 */
	public static Map<String,String> processor(String result,ZfbMember zfbMember){
		Map<String, String> map = new HashMap<String,String>();
		map.put("status", "success") ;
		if(StrUtil.isBlank(result)) {
			map.put("status", "error") ;
			return map ;
		}
		JSONObject json = JSON.parseObject(result);
		String status = json.getString("status");
		if(!status.equals("succeed")) {
			map.put("status", "warning") ;
		}else {
			JSONObject resultJson = json.getJSONObject("result");
			JSONArray details = resultJson.getJSONArray("detail");
			List<ZfbInLog> list = new ArrayList<ZfbInLog>(); //这边存放的全部都是到款记录
			for(int i=details.size() - 1;i>=0;i--) {
				JSONObject detail = details.getJSONObject(i);
				String tradeNo = detail.getString("tradeNo");
				boolean exists = FunctionUtils.isBloomFilter(tradeNo);
				//boolean exists = false ;
				
				if(!exists) {
					//如果不存在，那么是新收款的
					//按接口区分返回参数
					BigDecimal tradeAmount = detail.getBigDecimal("tradeAmount");
					String goodsTitle = detail.getString("goodsTitle");
					if(StrUtil.isBlank(goodsTitle)) {
						String transMemo = detail.getString("transMemo");
						int index = transMemo.indexOf("-");
						if(index == -1) {
							//那么是没有
							goodsTitle = transMemo ;
						}else {
							goodsTitle = transMemo.substring(0,index) ; 
						}
					}
					Pattern pattern = Pattern.compile("b=(.+)");
					Matcher matcher = pattern.matcher(goodsTitle);
					if(matcher.find()) {
						//匹配成功
						goodsTitle = matcher.group(1) ;
					}else {
						continue ; 
					}
					
					
					String otherAccountFullname = detail.getString("otherAccountFullname");
					ZfbInLog log = new ZfbInLog();
					log.setMemberId(zfbMember.getId());
					log.setMoney(tradeAmount);
					log.setCreatetime(new Date());
					log.setTradeNo(tradeNo);
					log.setFlagcode(goodsTitle);
					log.setTransname(otherAccountFullname);
					System.out.println(log);
					list.add(log) ;
				}
			}
			map.put("data", JSON.toJSONString(list)) ;
		}

		return map ; 
	}
}
